package client.ui.view.panel.main;

import client.UserState;
import client.assets.Icons;
import client.connect.HttpConnect;
import client.control.Controller;
import client.control.ResponseEntity;
import client.entity.User;
import client.ui.component.card.Card;
import client.ui.component.edittext.TextEdit;
import client.ui.component.scroll.SmallMouseWheelListener;
import client.ui.theme.ThisFont;
import client.ui.util.MaterialColors;
import client.ui.view.GoodsPage;
import client.ui.view.base.PanelControl;
import com.alibaba.fastjson.JSONObject;
import client.entity.Good;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

/**
  * @Description 购物车面板
  * @author 孔明浩
  * @Date 2020/3/31
  */
public class CartPanel extends JPanel implements PanelControl {
    private Executor singleThreadExecutor = Executors.newSingleThreadExecutor();
    private List<Good> cartGoods = new ArrayList<>();
    JPanel itemPanel;
    public CartPanel(){
        super();
        PanelControl.panels.put("CartPanel",this);
        initial();
        getCartList();
    }

    //初始化购物车面板
    private void initial(){
        GridBagLayout gridBagLayout = new GridBagLayout();
        GridBagConstraints gridBagConstraints;
        this.setLayout(gridBagLayout);
        this.setBackground(MaterialColors.TEAL_50);

        //添加搜索面板
        JPanel searchPanel = new JPanel(new BorderLayout());
        TextEdit search = new TextEdit("搜索购物车");
        search.setEndImage(Icons.search);
        search.getEndLabel().addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                search.setEndImage(Icons.search);
                System.out.println("搜索购物车:" + search.getText());
            }
            @Override
            public void mouseEntered(MouseEvent e) {
                search.setEndImage(Icons.search1);
            }
            @Override
            public void mouseExited(MouseEvent e) {
                search.setEndImage(Icons.search);
            }
        });
        searchPanel.add(search,BorderLayout.EAST);
        searchPanel.setBorder(new EmptyBorder(12,24,12,24));

        //添加标题面板
        JLabel titleLabel = new JLabel("购物车");
        titleLabel.setBorder(new EmptyBorder(0,24,0,24));
        titleLabel.setForeground(MaterialColors.COSMO_BLUE);
        titleLabel.setFont(ThisFont.VERY_BIG_BOLD_FONT);
        searchPanel.setBackground(MaterialColors.GRAY_300);
        search.setBackground(MaterialColors.GRAY_300);
        searchPanel.add(titleLabel, BorderLayout.WEST);

        //添加物品面板
        GridLayout gridLayout = new GridLayout(0,4);
        gridLayout.setHgap(16);
        gridLayout.setVgap(4);
        itemPanel = new JPanel(gridLayout);
        itemPanel.add(new JLabel());
        itemPanel.add(new JLabel());
        itemPanel.add(new JLabel());

        Box vBox = Box.createVerticalBox();
        vBox.add(itemPanel);
        //物品面板
        JScrollPane scrollPane = new JScrollPane(vBox);
        JScrollBar vScrollBar = scrollPane.getVerticalScrollBar();
        //滚动事件重写
        scrollPane.addMouseWheelListener(new SmallMouseWheelListener(30, vScrollBar));
        scrollPane.setBorder(null);
        scrollPane.setWheelScrollingEnabled(false);

        this.add(searchPanel);
        gridBagConstraints = new GridBagConstraints();
        gridBagConstraints.weightx = 1;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = GridBagConstraints.HORIZONTAL;
        gridBagLayout.addLayoutComponent(searchPanel,gridBagConstraints);

        this.add(scrollPane);
        gridBagConstraints = new GridBagConstraints();
        gridBagConstraints.weightx = 1;
        gridBagConstraints.weighty = 1;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.fill = GridBagConstraints.BOTH;
        gridBagLayout.addLayoutComponent(scrollPane,gridBagConstraints);

    }

    /**
     * @Description
     * @param object User类型更新面板
     * @return void
     * @author 孔明浩
     * @Date 2020/4/6
     */
    @Override
    public void updatePanel(Object object) {
        if (object instanceof User){
            User user = (User) object;
            List<Integer> list = JSONObject.parseArray(user.getCart(),Integer.class);
            cartGoods.clear();
            for (int id:list) {
                ResponseEntity responseEntity = Controller.GOOD_CONTROL.getGoodInfo(id);
                if (responseEntity.getCode() == 0){
                    cartGoods.add(JSONObject.parseObject(responseEntity.getData(), Good.class));
                }
            }
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    itemPanel.removeAll();
                    for (Good g:cartGoods) {
                        List<String> urls = JSONObject.parseArray(g.getPic(), String.class);
                        String url = "";
                        try{
                            url = urls.get(0);
                        } catch (Exception e){
                            e.printStackTrace();
                        }
                        String finalUrl = url;
                        Card card = new Card(g.getGoodId(), finalUrl,g.getGoodName(),g.getPrice());
                        card.addMouseListener(new MouseAdapter() {
                            @Override
                            public void mouseClicked(MouseEvent e) {
                                //商品展示界面
                                JFrame page = new GoodsPage(g.getGoodName(),g);
                            }
                        });
                        JPopupMenu popupMenu = new JPopupMenu();
                        JMenuItem delete = new JMenuItem("取消收藏");
                        delete.addActionListener(new ActionListener() {
                            @Override
                            public void actionPerformed(ActionEvent e) {
                                singleThreadExecutor.execute(new Runnable() {
                                    @Override
                                    public void run() {
                                        ResponseEntity responseEntity = Controller.GOOD_CONTROL.deleteCart(UserState.getToken(),g.getGoodId());
                                        if (responseEntity.getCode() == 0){
                                            showMessage("删除成功");
                                            getCartList();
                                        } else {
                                            showMessage( "删除失败");
                                        }
                                    }
                                });
                            }
                        });
                        popupMenu.add(delete);

                        card.setComponentPopupMenu(popupMenu);
                        itemPanel.add(card);

                    }
                    //占位Label
                    itemPanel.add(new JLabel());
                    itemPanel.add(new JLabel());
                    itemPanel.add(new JLabel());
                    itemPanel.add(new JLabel());
                    itemPanel.validate();
                    //防止重影
                    itemPanel.repaint();
                }
            });
        }
    }

    /**
     * @Description 通过更新我的商品列表,更新myItems
     * @author 孔明浩
     * @Date 2020/4/5
     */
    public void getCartList(){
        singleThreadExecutor.execute(new Runnable() {
            @Override
            public void run() {
                ResponseEntity responseEntity = Controller.USER_CONTROL.getUserInfo(UserState.getToken());
                if (responseEntity.getCode() == 0){
                    UserState.setUser(JSONObject.parseObject(responseEntity.getData(),User.class));
                    updatePanel(JSONObject.parseObject(responseEntity.getData(),User.class));
                }
            }
        });
    }

    private void showMessage(String message){
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                JOptionPane.showMessageDialog(CartPanel.this,message);
            }
        });
    }
}
